package com.hm.ipay.controller;

import com.hm.ipay.comm.aop.LoggerManage;
import com.hm.ipay.dao.ValidateMapper;
import com.hm.ipay.domain.RegisterResult;
import com.hm.ipay.domain.result.ExceptionMsg;
import com.hm.ipay.domain.result.ResponseData;
import com.hm.ipay.domain.result.ResponseDataList;
import com.hm.ipay.entity.PushRecord;
import com.hm.ipay.entity.UserAccount;
import com.hm.ipay.entity.Validate;
import com.hm.ipay.service.UserService;
import com.hm.ipay.utils.Jdpush;
import com.hm.ipay.utils.MathUtil;
import com.hm.ipay.utils.ShareCodeUtil;
import com.hm.ipay.utils.ValidateCode;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.text.ParsePosition;
import java.text.SimpleDateFormat;
import java.util.*;


@RestController
public class UserController {

    @Autowired
    UserService userService;

    @Autowired
    ValidateMapper validateMapper;

    private static String ENCODING = "UTF-8";

    private static String URI_SEND_SMS = "https://sms.yunpian.com/v2/sms/single_send.json";

    @RequestMapping(value = "/register", method = RequestMethod.POST)
    @LoggerManage(description = "注册")
    public ResponseData register(UserAccount userAccount) {
        try {
            String inviteCode = userAccount.getInviteCode();
            if (!StringUtils.isEmpty(inviteCode)) {
                UserAccount invitor_lv2 = userService.findInvitor(inviteCode);
                if (invitor_lv2 != null) {
                    userAccount.setSecondaryBeneficiary(invitor_lv2.getId());
                    if (!StringUtils.isEmpty(invitor_lv2.getSecondaryBeneficiary())) {
                        userAccount.setPrimaryBeneficiary(invitor_lv2.getSecondaryBeneficiary());
                    }
                }
            } else if (StringUtils.isEmpty(userAccount.getUserName())) {
                return new ResponseData(ExceptionMsg.MissUserName);
            } else if (StringUtils.isEmpty(userAccount.getTel())) {
                return new ResponseData(ExceptionMsg.MissTel);
            } else if (StringUtils.isEmpty(userAccount.getPassword())) {
                return new ResponseData(ExceptionMsg.MissPassword);
            } else if (StringUtils.isEmpty(userAccount.getPayPassword())) {
                return new ResponseData(ExceptionMsg.MissPayPassword);
            }
            userAccount.setInviteCode(ShareCodeUtil.idToCode(userAccount.getTel()));
            userService.register(userAccount);
        } catch (DuplicateKeyException e) {
            return new ResponseData(ExceptionMsg.TelInUsed);
        } catch (Exception e) {
            return new ResponseData(ExceptionMsg.FAILED);
        }
        return new ResponseData(ExceptionMsg.SUCCESS, new RegisterResult(userAccount.getId()));
    }

    @RequestMapping(value = "/login", method = RequestMethod.POST)
    @LoggerManage(description = "登录")
    public ResponseData login(UserAccount userAccount, HttpServletRequest request) {
        //String code = request.getParameter("code");
//        HttpSession session = request.getSession();
//        System.out.println((String) session.getAttribute("code"));
        try {
            if (StringUtils.isEmpty(userAccount.getTel())) {
                return new ResponseData(ExceptionMsg.MissTel);
            } else if (StringUtils.isEmpty(userAccount.getPassword())) {
                return new ResponseData(ExceptionMsg.MissPassword);
            }
            UserAccount loginAccount = userService.login(userAccount.getTel());
            if (loginAccount == null) {
                return new ResponseData(ExceptionMsg.UserNotFound);
            } else if (!userAccount.getPassword().equals(loginAccount.getPassword())) {
                return new ResponseData(ExceptionMsg.PasswordError);
            }
            return new ResponseData(ExceptionMsg.SUCCESS, new RegisterResult(loginAccount.getId()));
        } catch (Exception e) {
            return new ResponseData(ExceptionMsg.FAILED);
        }
    }


    @RequestMapping(value = "/validate_pic", method = RequestMethod.POST)
    @LoggerManage(description = "图形验证码")
    public String validatePic(HttpServletRequest request, HttpServletResponse response) throws Exception {
        // 设置响应的类型格式为图片格式
        response.setContentType("image/jpeg");
        //禁止图像缓存。
        response.setHeader("Pragma", "no-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expires", 0);

        HttpSession session = request.getSession();

        ValidateCode vCode = new ValidateCode(120,40,5,100);
        session.setAttribute("code", vCode.getCode());
        response.setHeader("vCode", vCode.getCode());
        vCode.write(response.getOutputStream());
        return null;
    }

    @RequestMapping(value = "/bg/validate_pic", method = RequestMethod.GET)
    @LoggerManage(description = "图形验证码")
    public String validatePicBack(HttpServletRequest request, HttpServletResponse response) throws Exception {
        // 设置响应的类型格式为图片格式
        response.setContentType("image/jpeg");
        //禁止图像缓存。
        response.setHeader("Pragma", "no-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expires", 0);

        HttpSession session = request.getSession();

        ValidateCode vCode = new ValidateCode(120,40,5,100);
        session.setAttribute("code", vCode.getCode());
        response.setHeader("vCode", vCode.getCode());
        vCode.write(response.getOutputStream());
        Validate validate = new Validate();
        validate.setCode(vCode.getCode());
        validateMapper.insert(validate);
        return null;
    }

    @RequestMapping(value = "/reset_password", method = RequestMethod.POST)
    @LoggerManage(description = "重置密码")
    public ResponseData resetPassword(String mobile, String password) {
        userService.resetPassword(mobile, password);
        return new ResponseData(ExceptionMsg.SUCCESS);
    }

    @RequestMapping(value = "/sms_auth_code", method = RequestMethod.POST)
    @LoggerManage(description = "短信验证码")
    public ResponseData smsAuthCode(String mobile) {
        String content = null;
        try {
            content = sendSms(mobile);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return new ResponseData(ExceptionMsg.SUCCESS, content);
    }

//    private String sendSms(String phoneNum) {
//        System.setProperty("sun.net.client.defaultConnectTimeout", "30000");
//        System.setProperty("sun.net.client.defaultReadTimeout", "30000");
//        StringBuffer buffer = new StringBuffer();
//        String encode = "UTF-8";
//        String username = "fxggr";
//        String password_md5 = "5d93ceb70e2bf5daa84ec3d0cd2c731a";
//        String mobile = phoneNum;
//        String apikey = "3484e84dee9bec09cb8e0b87689d8090";
//        String contentNum = String.valueOf(MathUtil.randomCode());
//        String content = "您的验证码: " + contentNum;
//        try {
//            String contentUrlEncode = URLEncoder.encode(content,encode);
//            buffer.append("http://m.5c.com.cn/api/send/index.php?username="+username+"&password_md5="+password_md5+"&mobile="+mobile+"&apikey="+apikey+"&content="+contentUrlEncode+"&encode="+encode);
//            URL url = new URL(buffer.toString());
//            HttpURLConnection connection = (HttpURLConnection)url.openConnection();
//            connection.setRequestMethod("POST");
//            connection.setRequestProperty("Connection", "Keep-Alive");
//            BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream()));
//            String result = reader.readLine();
//            System.out.println(result);
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//        return contentNum;
//    }

    private static String sendSms(String mobile) throws IOException {
        String contentNum = String.valueOf(MathUtil.randomCode());
        String content = "【_SAEJIN】verify code " + contentNum;
        Map<String, String> params = new HashMap<String, String>();
        params.put("apikey", "22be12ae08c1a84ec6d8fff83ae72c22");
        params.put("text", content);
        params.put("mobile", mobile);
        post(URI_SEND_SMS, params);
        return contentNum;
    }

    private static String post(String url, Map<String, String> paramsMap) {
        CloseableHttpClient client = HttpClients.createDefault();
        String responseText = "";
        CloseableHttpResponse response = null;
        try {
            HttpPost method = new HttpPost(url);
            if (paramsMap != null) {
                List<NameValuePair> paramList = new ArrayList<NameValuePair>();
                for (Map.Entry<String, String> param : paramsMap.entrySet()) {
                    NameValuePair pair = new BasicNameValuePair(param.getKey(), param.getValue());
                    paramList.add(pair);
                }
                method.setEntity(new UrlEncodedFormEntity(paramList, ENCODING));
            }
            response = client.execute(method);
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                responseText = EntityUtils.toString(entity);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                response.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }                                                                                                                                                                                                                                                                                                                       System.out.println(responseText);//此处打印在console后，会给出一个IP地址
        return responseText;
    }

    @RequestMapping(value = "/bg/send_push", method = RequestMethod.POST)
    @LoggerManage(description = "发送推送")
    public ResponseData sendPush(String alert, String title, String scheduleTime) {
        PushRecord record = new PushRecord();
        record.setTitle(title);
        record.setContent(alert);
        if (!StringUtils.isEmpty(scheduleTime)) {
            SimpleDateFormat formatter = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
            ParsePosition pos = new ParsePosition(0);
            Date date = formatter.parse(scheduleTime, pos);
            Date pushDate = (Date)date.clone();
            date.setHours(date.getHours() + 8);
            record.setScheduleTime(date);
            int messageId = userService.insertMessage(record);
            Jdpush.sendSchedulePushAll(alert, title, pushDate,"定时推送", String.valueOf(record.getId()));
        } else {
            int messageId = userService.insertMessage(record);
            Jdpush.testSendPush(alert, title, String.valueOf(record.getId()));
        }
        return new ResponseData(ExceptionMsg.SUCCESS);
    }

    @RequestMapping(value = "/bg/message_list", method = RequestMethod.POST)
    @LoggerManage(description = "后台推送信息列表")
    public ResponseDataList bgMessageList(Integer limit, Integer offset) {
        return userService.bgMessageList(limit, offset);
    }

    @RequestMapping(value = "/message_list", method = RequestMethod.POST)
    @LoggerManage(description = "推送信息列表")
    public ResponseDataList messageList(Integer limit, Integer offset) {
        return userService.messageList(limit, offset);
    }

    @RequestMapping(value = "/bg/del_message", method = RequestMethod.POST)
    @LoggerManage(description = "删除消息")
    public ResponseData delMessage(Long id) {
        return userService.delMessage(id);
    }

    @RequestMapping(value = "/bg/get_message", method = RequestMethod.POST)
    @LoggerManage(description = "获取消息")
    public ResponseData getMessage(Long id) {
        return userService.getMessage(id);
    }

    @RequestMapping(value = "/bg/update_message", method = RequestMethod.POST)
    @LoggerManage(description = "修改消息")
    public ResponseData updateMessage(PushRecord record) {
        return userService.updateMessage(record);
    }

    @RequestMapping(value = "/set_reg_id", method = RequestMethod.POST)
    @LoggerManage(description = "设置用户设备码")
    public ResponseData setRegistrationId(Long userId, String regId) {
        return userService.setRegistrationId(userId, regId);
    }
}
